<template>
  <div class="app">
    <a-button type="primary" @click="handleClick">运行</a-button>
    <div class="codemirror">
      <codemirror
        v-model="code"
        placeholder="Code goes here..."
        :autofocus="true"
        :indent-with-tab="true"
        :tab-size="2"
        :extensions="extensions"
        @ready="handleReady"
        @change="changeCode('change', $event)"
        @focus="log('focus', $event)"
        @blur="log('blur', $event)"
      />
    </div>
    <div class="code-running">
      <CodePreview v-model:code="code" />
    </div>
  </div>
</template>

<script setup>
import CodePreview from './CodePreview'
import { h, defineComponent } from 'vue'
import { Codemirror } from 'vue-codemirror'
import { javascript } from '@codemirror/lang-javascript'
import { oneDark } from '@codemirror/theme-one-dark'

const code = ref(`<a-button type="primary" @click="handleClick">运行</a-button>`)
const extensions = [javascript(), oneDark]

// Codemirror EditorView instance ref
const view = shallowRef()
const handleReady = (payload) => {
  view.value = payload.view
}

// Status is available at all times via Codemirror EditorView
const getCodemirrorStates = () => {
  const state = view.value.state
  const ranges = state.selection.ranges
  const selected = ranges.reduce((r, range) => r + range.to - range.from, 0)
  const cursor = ranges[0].anchor
  const length = state.doc.length
  const lines = state.doc.lines
  // more state info ...
  // return ...
}

const handleClick = () => {
  console.log(code, extensions, handleReady)
}

const changeCode = (type, content) => {
  console.log(type, content)
  code.value = content
  console.log(code.value)
}

const log = console.log
</script>
<style lang="scss" scoped>
.app {
  display: flex;
  height: 100%;
  div {
    height: 100%;
  }
  .codemirror {
    width: 50%;
    height: 100%;
  }
  .code-running {
    width: 50%;
    background-color: #f6f6f6;
  }
}
</style>
